import React, { useEffect } from 'react';
import { Button, Card, message } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import ProDescriptions from '@ant-design/pro-descriptions';
import { ModalForm, ProFormText, ProFormUploadButton } from '@ant-design/pro-form';
import { connect, FormattedMessage, useIntl } from 'umi';
import moment from 'moment';
import { ethers } from 'ethers';
import { readFilePromise } from '@/utils/utils';

const UserSetting = (props) => {
  const { dispatch, currentUser, user, status } = props;
  const intl = useIntl();

  useEffect(() => {
    if (status) {
      return;
    }
    dispatch({
      type: 'userSetting/getUser',
      payload: { userID: currentUser.id },
    });
  }, [status]);

  const columns = [
    {
      title: <FormattedMessage id="pages.user.setting.mail" />,
      dataIndex: 'mail',
    },
    {
      title: <FormattedMessage id="pages.user.setting.username" />,
      dataIndex: 'username',
    },
    {
      title: <FormattedMessage id="pages.user.setting.createdAt" />,
      dataIndex: 'createdAt',
      render: (_, record) => {
        return (
          <>
            {record.createdAt > 0
              ? moment.unix(record.createdAt).format('YYYY-MM-DD HH:mm:ss')
              : ''}
          </>
        );
      },
    },
    {
      title: <FormattedMessage id="pages.user.setting.address" />,
      tooltip: intl.formatMessage({ id: 'pages.user.setting.address.tooltip' }),
      dataIndex: 'address',
    },
  ];

  const onFinish = async (values) => {
    try {
      const file = await readFilePromise(values.keystore[0].originFileObj);
      const wallet = await ethers.Wallet.fromEncryptedJson(file, values.password);
      dispatch({
        type: 'userSetting/addAccount',
        payload: { userID: currentUser.id, address: wallet.address },
      });
    } catch (e) {
      message.error(e.message);
      return false;
    }
    return true;
  };

  const newAccountForm = (
    <ModalForm
      title={
        <FormattedMessage
          id="pages.user.setting.form.title"
          defaultMessage="pages.user.setting.form.title"
        />
      }
      trigger={
        <Button type="primary">
          <FormattedMessage id="pages.user.setting.button" />
        </Button>
      }
      onFinish={onFinish}
    >
      <ProFormUploadButton
        name="keystore"
        label="密钥文件"
        // accept='.txt,.json'
        listType={'text'}
        max={1}
        rules={[
          {
            required: true,
            message: <FormattedMessage id="pages.setting.keystore.required" />,
          },
        ]}
      />
      <ProFormText.Password
        name="password"
        label="密码"
        rules={[
          {
            required: true,
            message: <FormattedMessage id="pages.setting.password.required" />,
          },
        ]}
      />
    </ModalForm>
  );

  return (
    <PageContainer>
      <Card bordered={false}>
        <ProDescriptions
          extra={newAccountForm}
          title={<FormattedMessage id="pages.user.setting.title" />}
          column={2}
          columns={columns}
          dataSource={user}
        />
      </Card>
    </PageContainer>
  );
};

export default connect(({ user, userSetting }) => ({
  user: userSetting.user,
  status: userSetting.status,
  currentUser: user.currentUser,
}))(UserSetting);
